package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;


    @Scheduled(cron = "0 0 * * * ? ")
    public void  processTimeoutOrder(){
        log.info("定时处理未付款{}", LocalDateTime.now());
        //根据状态查订单
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime localDateTime = now.plusMinutes(-15);
        List<Orders> orders= orderMapper.getByStatusAndOrdertimeLT(Orders.PENDING_PAYMENT,localDateTime);
        //更改订单信息
        if(orders!=null&&orders.size()>0){
            for(Orders order:orders){
                order.setCancelReason("超时");
                order.setCancelTime(LocalDateTime.now());
                order.setStatus(Orders.CANCELLED);
                //取消订单
                orderMapper.update(order);
            }
        }
    }

    //处理完成订单，1点执行，提前一小时，把前面的都取消了,现在测试改成每小时一次
    @Scheduled(cron = "0 0 * * * ? ")
    public void processDeliveryOrder(){
        log.info("完成订单{}", LocalDateTime.now());
        //根据状态查订单
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime localDateTime = now.plusMinutes(-60);
        List<Orders> orders= orderMapper.getByStatusAndOrdertimeLT(Orders.DELIVERY_IN_PROGRESS,localDateTime);
        //更改订单信息
        if(orders!=null&&orders.size()>0){
            orders.forEach(order -> {
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            });
        }
    }
}
